//
//  UIColorExtension.swift
//  AFNetworking
//
//  Created by Max on 2019/7/4.
//

import UIKit
import SwiftUI

public extension UIColor {
    
    convenience init?(_ hex: String?) {
        guard let hex = hex else {
            return nil
        }
        self.init(hexString: hex)
    }
    
    convenience init?(hexString: String, alpha: CGFloat = 1) {
        var string = ""
        if hexString.lowercased().hasPrefix("0x") {
            string =  hexString.replacingOccurrences(of: "0x", with: "")
        } else if hexString.hasPrefix("#") {
            string = hexString.replacingOccurrences(of: "#", with: "")
        } else {
            string = hexString
        }
        
        if string.count == 3 { // convert hex to 6 digit format if in short format
            var str = ""
            string.forEach { str.append(String(repeating: String($0), count: 2)) }
            string = str
        }
        
        guard let hexValue = Int(string, radix: 16) else { return nil }
        
        var trans = alpha
        if trans < 0 { trans = 0 }
        if trans > 1 { trans = 1 }
        
        let red = (hexValue >> 16) & 0xff
        let green = (hexValue >> 8) & 0xff
        let blue = hexValue & 0xff
        self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: alpha)
    }
    
    static func color(optionalHexString: String?, defaultColor: UIColor) -> UIColor {
        guard let hexString = optionalHexString, !hexString.isEmpty, let color = UIColor(hexString: hexString) else {
            return defaultColor
        }
        return color
    }
}

public extension UIColor {
    var color: SwiftUI.Color {
        var r: CGFloat = 0
        var g: CGFloat = 0
        var b: CGFloat = 0
        var a: CGFloat = 0
        
        if let components = cgColor.components, components.count == 4 {
            r = components[0]
            g = components[1]
            b = components[2]
            a = components[3]
        }
        else {
            getRed(&r, green: &g, blue: &b, alpha: &a)
        }
        
        return SwiftUI.Color(red: r, green: g, blue: b, opacity: a)
    }
}
